import React, { useState, useEffect } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Table,
  Tag,
  Button,
  Space,
  Typography,
  Alert,
  List,
  Avatar,
  Tooltip,
  Select,
  DatePicker,
  Badge,
  Tabs,
  Timeline,
  Descriptions,
  Modal,
  message
} from 'antd';
import {
  MonitorOutlined,
  DatabaseOutlined,
  ApiOutlined,
  UserOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  SettingOutlined,
  BellOutlined,
  LineChartOutlined,
  BarChartOutlined,
  DashboardOutlined,
  CloudOutlined,
  SafetyOutlined,
  ThunderboltOutlined,
  EyeOutlined,
  DesktopOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';

dayjs.extend(relativeTime);

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Title, Text } = Typography;
// const { TabPane } = Tabs; // Deprecated, using items instead

interface SystemMetrics {
  cpu: {
    usage: number;
    cores: number;
    load: number[];
  };
  memory: {
    total: number;
    used: number;
    free: number;
    usage: number;
  };
  disk: {
    total: number;
    used: number;
    free: number;
    usage: number;
  };
  network: {
    inbound: number;
    outbound: number;
    connections: number;
  };
}

interface ServiceStatus {
  id: string;
  name: string;
  status: 'running' | 'stopped' | 'error' | 'warning';
  uptime: string;
  cpu: number;
  memory: number;
  responseTime: number;
  lastCheck: string;
  port?: number;
  version?: string;
}

interface AlertRule {
  id: string;
  name: string;
  type: string;
  condition: string;
  threshold: number;
  severity: 'low' | 'medium' | 'high' | 'critical';
  enabled: boolean;
  lastTriggered?: string;
  description: string;
}

interface Alert {
  id: string;
  ruleId: string;
  ruleName: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
  message: string;
  status: 'active' | 'resolved' | 'acknowledged';
  createdAt: string;
  resolvedAt?: string;
  acknowledgedBy?: string;
  details: any;
}

interface PerformanceMetric {
  timestamp: string;
  cpu: number;
  memory: number;
  disk: number;
  network: number;
  responseTime: number;
  throughput: number;
}

const MonitoringCenter: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [activeTab, setActiveTab] = useState('overview');
  const [systemMetrics, setSystemMetrics] = useState<SystemMetrics | null>(null);
  const [serviceStatuses, setServiceStatuses] = useState<ServiceStatus[]>([]);
  const [alertRules, setAlertRules] = useState<AlertRule[]>([]);
  const [alerts, setAlerts] = useState<Alert[]>([]);
  const [performanceData, setPerformanceData] = useState<PerformanceMetric[]>([]);
  const [selectedAlert, setSelectedAlert] = useState<Alert | null>(null);
  const [alertModalVisible, setAlertModalVisible] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [refreshInterval, setRefreshInterval] = useState(30);

  useEffect(() => {
    loadMonitoringData();
    
    let interval: NodeJS.Timeout;
    if (autoRefresh) {
      interval = setInterval(loadMonitoringData, refreshInterval * 1000);
    }
    
    return () => {
      if (interval) clearInterval(interval);
    };
  }, [autoRefresh, refreshInterval]);

  const loadMonitoringData = async () => {
    setLoading(true);
    try {
      await Promise.all([
        loadSystemMetrics(),
        loadServiceStatuses(),
        loadAlertRules(),
        loadAlerts(),
        loadPerformanceData()
      ]);
    } catch (error) {
      message.error('加载监控数据失败');
    } finally {
      setLoading(false);
    }
  };

  const loadSystemMetrics = async () => {
    const mockMetrics: SystemMetrics = {
      cpu: {
        usage: 45.6,
        cores: 8,
        load: [0.8, 1.2, 0.9]
      },
      memory: {
        total: 16 * 1024 * 1024 * 1024, // 16GB
        used: 8.5 * 1024 * 1024 * 1024, // 8.5GB
        free: 7.5 * 1024 * 1024 * 1024, // 7.5GB
        usage: 53.1
      },
      disk: {
        total: 500 * 1024 * 1024 * 1024, // 500GB
        used: 320 * 1024 * 1024 * 1024, // 320GB
        free: 180 * 1024 * 1024 * 1024, // 180GB
        usage: 64.0
      },
      network: {
        inbound: 125.6, // MB/s
        outbound: 89.3, // MB/s
        connections: 1250
      }
    };
    setSystemMetrics(mockMetrics);
  };

  const loadServiceStatuses = async () => {
    const mockServices: ServiceStatus[] = [
      {
        id: 'web-server',
        name: 'Web服务器',
        status: 'running',
        uptime: '15天 8小时',
        cpu: 12.5,
        memory: 256,
        responseTime: 45,
        lastCheck: '2024-01-15 14:30:00',
        port: 8000,
        version: '1.2.3'
      },
      {
        id: 'database',
        name: '数据库服务',
        status: 'running',
        uptime: '15天 8小时',
        cpu: 25.8,
        memory: 1024,
        responseTime: 12,
        lastCheck: '2024-01-15 14:30:00',
        port: 5432,
        version: '13.4'
      },
      {
        id: 'redis',
        name: 'Redis缓存',
        status: 'running',
        uptime: '15天 8小时',
        cpu: 5.2,
        memory: 128,
        responseTime: 2,
        lastCheck: '2024-01-15 14:30:00',
        port: 6379,
        version: '6.2.6'
      },
      {
        id: 'message-queue',
        name: '消息队列',
        status: 'warning',
        uptime: '2天 3小时',
        cpu: 8.9,
        memory: 64,
        responseTime: 156,
        lastCheck: '2024-01-15 14:30:00',
        port: 5672,
        version: '3.8.9'
      },
      {
        id: 'file-storage',
        name: '文件存储',
        status: 'error',
        uptime: '0分钟',
        cpu: 0,
        memory: 0,
        responseTime: 0,
        lastCheck: '2024-01-15 14:25:00',
        port: 9000
      }
    ];
    setServiceStatuses(mockServices);
  };

  const loadAlertRules = async () => {
    const mockRules: AlertRule[] = [
      {
        id: 'cpu-high',
        name: 'CPU使用率过高',
        type: 'system',
        condition: 'cpu_usage > threshold',
        threshold: 80,
        severity: 'high',
        enabled: true,
        lastTriggered: '2024-01-14 16:20:00',
        description: 'CPU使用率超过80%时触发告警'
      },
      {
        id: 'memory-high',
        name: '内存使用率过高',
        type: 'system',
        condition: 'memory_usage > threshold',
        threshold: 85,
        severity: 'high',
        enabled: true,
        description: '内存使用率超过85%时触发告警'
      },
      {
        id: 'disk-full',
        name: '磁盘空间不足',
        type: 'system',
        condition: 'disk_usage > threshold',
        threshold: 90,
        severity: 'critical',
        enabled: true,
        description: '磁盘使用率超过90%时触发告警'
      },
      {
        id: 'service-down',
        name: '服务不可用',
        type: 'service',
        condition: 'service_status == down',
        threshold: 0,
        severity: 'critical',
        enabled: true,
        lastTriggered: '2024-01-15 14:25:00',
        description: '关键服务停止运行时触发告警'
      },
      {
        id: 'response-slow',
        name: '响应时间过慢',
        type: 'performance',
        condition: 'response_time > threshold',
        threshold: 1000,
        severity: 'medium',
        enabled: true,
        description: '接口响应时间超过1秒时触发告警'
      }
    ];
    setAlertRules(mockRules);
  };

  const loadAlerts = async () => {
    const mockAlerts: Alert[] = [
      {
        id: 'alert001',
        ruleId: 'service-down',
        ruleName: '服务不可用',
        severity: 'critical',
        message: '文件存储服务已停止运行',
        status: 'active',
        createdAt: '2024-01-15 14:25:00',
        details: {
          service: 'file-storage',
          port: 9000,
          error: 'Connection refused'
        }
      },
      {
        id: 'alert002',
        ruleId: 'response-slow',
        ruleName: '响应时间过慢',
        severity: 'medium',
        message: '消息队列响应时间过慢',
        status: 'acknowledged',
        createdAt: '2024-01-15 13:45:00',
        acknowledgedBy: '管理员',
        details: {
          service: 'message-queue',
          responseTime: 156,
          threshold: 100
        }
      },
      {
        id: 'alert003',
        ruleId: 'cpu-high',
        ruleName: 'CPU使用率过高',
        severity: 'high',
        message: 'CPU使用率达到85%',
        status: 'resolved',
        createdAt: '2024-01-14 16:20:00',
        resolvedAt: '2024-01-14 16:35:00',
        details: {
          cpuUsage: 85.2,
          threshold: 80
        }
      }
    ];
    setAlerts(mockAlerts);
  };

  const loadPerformanceData = async () => {
    const mockData: PerformanceMetric[] = Array.from({ length: 24 }, (_, i) => ({
      timestamp: dayjs().subtract(23 - i, 'hour').format('HH:mm'),
      cpu: Math.random() * 80 + 10,
      memory: Math.random() * 70 + 20,
      disk: Math.random() * 30 + 40,
      network: Math.random() * 200 + 50,
      responseTime: Math.random() * 100 + 20,
      throughput: Math.random() * 1000 + 500
    }));
    setPerformanceData(mockData);
  };

  const handleAcknowledgeAlert = async (alertId: string) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setAlerts(alerts.map(alert => 
        alert.id === alertId 
          ? { ...alert, status: 'acknowledged', acknowledgedBy: '当前用户' }
          : alert
      ));
      message.success('告警已确认');
    } catch (error) {
      message.error('确认告警失败');
    }
  };

  const handleResolveAlert = async (alertId: string) => {
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      setAlerts(alerts.map(alert => 
        alert.id === alertId 
          ? { ...alert, status: 'resolved', resolvedAt: dayjs().format('YYYY-MM-DD HH:mm:ss') }
          : alert
      ));
      message.success('告警已解决');
    } catch (error) {
      message.error('解决告警失败');
    }
  };

  const getStatusColor = (status: string) => {
    const colors = {
      running: 'green',
      stopped: 'red',
      error: 'red',
      warning: 'orange'
    };
    return colors[status as keyof typeof colors] || 'gray';
  };

  const getSeverityColor = (severity: string) => {
    const colors = {
      low: 'blue',
      medium: 'orange',
      high: 'red',
      critical: 'purple'
    };
    return colors[severity as keyof typeof colors] || 'gray';
  };

  const getAlertStatusColor = (status: string) => {
    const colors = {
      active: 'red',
      acknowledged: 'orange',
      resolved: 'green'
    };
    return colors[status as keyof typeof colors] || 'gray';
  };

  // 服务状态表格列
  const serviceColumns: ColumnsType<ServiceStatus> = [
    {
      title: '服务名称',
      key: 'service',
      render: (_, record) => (
        <Space>
          <Avatar 
            size="small" 
            icon={record.name.includes('数据库') ? <DatabaseOutlined /> : 
                  record.name.includes('Web') ? <DesktopOutlined /> : 
                  <ApiOutlined />} 
          />
          <div>
            <div style={{ fontWeight: 500 }}>{record.name}</div>
            <div style={{ fontSize: 12, color: '#666' }}>
              {record.port && `端口: ${record.port}`}
              {record.version && ` | 版本: ${record.version}`}
            </div>
          </div>
        </Space>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: string) => (
        <Badge 
          status={status === 'running' ? 'success' : status === 'error' ? 'error' : 'warning'} 
          text={
            <Tag color={getStatusColor(status)}>
              {status === 'running' ? '运行中' : 
               status === 'stopped' ? '已停止' : 
               status === 'error' ? '错误' : '警告'}
            </Tag>
          }
        />
      )
    },
    {
      title: '运行时间',
      dataIndex: 'uptime'
    },
    {
      title: 'CPU',
      dataIndex: 'cpu',
      render: (cpu: number) => (
        <div style={{ width: 80 }}>
          <Progress 
            percent={cpu} 
            size="small" 
            format={() => `${cpu.toFixed(1)}%`}
            strokeColor={cpu > 80 ? '#ff4d4f' : cpu > 60 ? '#faad14' : '#52c41a'}
          />
        </div>
      )
    },
    {
      title: '内存',
      dataIndex: 'memory',
      render: (memory: number) => `${memory}MB`
    },
    {
      title: '响应时间',
      dataIndex: 'responseTime',
      render: (time: number) => (
        <span style={{ color: time > 100 ? '#ff4d4f' : time > 50 ? '#faad14' : '#52c41a' }}>
          {time}ms
        </span>
      )
    },
    {
      title: '最后检查',
      dataIndex: 'lastCheck',
      render: (time: string) => (
        <Tooltip title={time}>
          {dayjs(time).fromNow()}
        </Tooltip>
      )
    }
  ];

  // 告警规则表格列
  const ruleColumns: ColumnsType<AlertRule> = [
    {
      title: '规则名称',
      dataIndex: 'name'
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: (type: string) => (
        <Tag color="blue">
          {type === 'system' ? '系统' : type === 'service' ? '服务' : '性能'}
        </Tag>
      )
    },
    {
      title: '条件',
      dataIndex: 'condition',
      ellipsis: true
    },
    {
      title: '阈值',
      dataIndex: 'threshold',
      render: (threshold: number, record) => 
        record.type === 'service' ? '-' : `${threshold}${record.type === 'performance' ? 'ms' : '%'}`
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      render: (severity: string) => (
        <Tag color={getSeverityColor(severity)}>
          {severity === 'low' ? '低' : 
           severity === 'medium' ? '中' : 
           severity === 'high' ? '高' : '严重'}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'enabled',
      render: (enabled: boolean) => (
        <Tag color={enabled ? 'green' : 'red'}>
          {enabled ? '启用' : '禁用'}
        </Tag>
      )
    },
    {
      title: '最后触发',
      dataIndex: 'lastTriggered',
      render: (time?: string) => time ? dayjs(time).fromNow() : '-'
    }
  ];

  // 告警列表表格列
  const alertColumns: ColumnsType<Alert> = [
    {
      title: '严重程度',
      dataIndex: 'severity',
      width: 100,
      render: (severity: string) => (
        <Tag color={getSeverityColor(severity)}>
          {severity === 'low' ? '低' : 
           severity === 'medium' ? '中' : 
           severity === 'high' ? '高' : '严重'}
        </Tag>
      )
    },
    {
      title: '规则名称',
      dataIndex: 'ruleName'
    },
    {
      title: '告警消息',
      dataIndex: 'message',
      ellipsis: true
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status: string) => (
        <Tag color={getAlertStatusColor(status)}>
          {status === 'active' ? '活跃' : 
           status === 'acknowledged' ? '已确认' : '已解决'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      render: (time: string) => dayjs(time).fromNow()
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            size="small" 
            icon={<EyeOutlined />}
            onClick={() => {
              setSelectedAlert(record);
              setAlertModalVisible(true);
            }}
          >
            详情
          </Button>
          {record.status === 'active' && (
            <Button 
              type="link" 
              size="small"
              onClick={() => handleAcknowledgeAlert(record.id)}
            >
              确认
            </Button>
          )}
          {record.status !== 'resolved' && (
            <Button 
              type="link" 
              size="small"
              onClick={() => handleResolveAlert(record.id)}
            >
              解决
            </Button>
          )}
        </Space>
      )
    }
  ];

  const formatBytes = (bytes: number) => {
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    if (bytes === 0) return '0 B';
    const i = Math.floor(Math.log(bytes) / Math.log(1024));
    return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
  };

  return (
    <div>
      {/* 页面标题和控制栏 */}
      <div style={{ marginBottom: 24 }}>
        <Row justify="space-between" align="middle">
          <Col>
            <Title level={3} style={{ margin: 0 }}>监控中心</Title>
          </Col>
          <Col>
            <Space>
              <Select 
                value={refreshInterval} 
                onChange={setRefreshInterval}
                style={{ width: 120 }}
              >
                <Option value={10}>10秒</Option>
                <Option value={30}>30秒</Option>
                <Option value={60}>1分钟</Option>
                <Option value={300}>5分钟</Option>
              </Select>
              <Button 
                type={autoRefresh ? 'primary' : 'default'}
                onClick={() => setAutoRefresh(!autoRefresh)}
              >
                {autoRefresh ? '停止自动刷新' : '开启自动刷新'}
              </Button>
              <Button icon={<ReloadOutlined />} onClick={loadMonitoringData} loading={loading}>
                手动刷新
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      {/* 监控标签页 */}
      <Tabs 
        activeKey={activeTab} 
        onChange={setActiveTab}
        items={[
          {
            key: 'overview',
            label: <span><DashboardOutlined />系统概览</span>,
            children: (
              <div>
                {systemMetrics && (
            <div>
              {/* 系统资源监控 */}
              <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="CPU使用率"
                      value={systemMetrics.cpu.usage}
                      precision={1}
                      suffix="%"
                      valueStyle={{ 
                        color: systemMetrics.cpu.usage > 80 ? '#ff4d4f' : 
                               systemMetrics.cpu.usage > 60 ? '#faad14' : '#52c41a' 
                      }}
                    />
                    <Progress 
                      percent={systemMetrics.cpu.usage} 
                      size="small" 
                      strokeColor={
                        systemMetrics.cpu.usage > 80 ? '#ff4d4f' : 
                        systemMetrics.cpu.usage > 60 ? '#faad14' : '#52c41a'
                      }
                      style={{ marginTop: 8 }}
                    />
                    <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
                      {systemMetrics.cpu.cores}核心 | 负载: {systemMetrics.cpu.load.join(', ')}
                    </div>
                  </Card>
                </Col>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="内存使用率"
                      value={systemMetrics.memory.usage}
                      precision={1}
                      suffix="%"
                      valueStyle={{ 
                        color: systemMetrics.memory.usage > 85 ? '#ff4d4f' : 
                               systemMetrics.memory.usage > 70 ? '#faad14' : '#52c41a' 
                      }}
                    />
                    <Progress 
                      percent={systemMetrics.memory.usage} 
                      size="small" 
                      strokeColor={
                        systemMetrics.memory.usage > 85 ? '#ff4d4f' : 
                        systemMetrics.memory.usage > 70 ? '#faad14' : '#52c41a'
                      }
                      style={{ marginTop: 8 }}
                    />
                    <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
                      {formatBytes(systemMetrics.memory.used)} / {formatBytes(systemMetrics.memory.total)}
                    </div>
                  </Card>
                </Col>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="磁盘使用率"
                      value={systemMetrics.disk.usage}
                      precision={1}
                      suffix="%"
                      valueStyle={{ 
                        color: systemMetrics.disk.usage > 90 ? '#ff4d4f' : 
                               systemMetrics.disk.usage > 75 ? '#faad14' : '#52c41a' 
                      }}
                    />
                    <Progress 
                      percent={systemMetrics.disk.usage} 
                      size="small" 
                      strokeColor={
                        systemMetrics.disk.usage > 90 ? '#ff4d4f' : 
                        systemMetrics.disk.usage > 75 ? '#faad14' : '#52c41a'
                      }
                      style={{ marginTop: 8 }}
                    />
                    <div style={{ fontSize: 12, color: '#666', marginTop: 4 }}>
                      {formatBytes(systemMetrics.disk.used)} / {formatBytes(systemMetrics.disk.total)}
                    </div>
                  </Card>
                </Col>
                <Col span={6}>
                  <Card>
                    <Statistic
                      title="网络连接数"
                      value={systemMetrics.network.connections}
                      valueStyle={{ color: '#722ed1' }}
                    />
                    <div style={{ fontSize: 12, color: '#666', marginTop: 8 }}>
                      入站: {systemMetrics.network.inbound.toFixed(1)} MB/s<br/>
                      出站: {systemMetrics.network.outbound.toFixed(1)} MB/s
                    </div>
                  </Card>
                </Col>
              </Row>

              {/* 活跃告警 */}
              {alerts.filter(alert => alert.status === 'active').length > 0 && (
                <Alert
                  message="系统告警"
                  description={
                    <div>
                      当前有 {alerts.filter(alert => alert.status === 'active').length} 个活跃告警需要处理
                      <List
                        size="small"
                        dataSource={alerts.filter(alert => alert.status === 'active').slice(0, 3)}
                        renderItem={(alert) => (
                          <List.Item>
                            <Tag color={getSeverityColor(alert.severity)}>
                              {alert.severity === 'critical' ? '严重' : 
                               alert.severity === 'high' ? '高' : 
                               alert.severity === 'medium' ? '中' : '低'}
                            </Tag>
                            {alert.message}
                          </List.Item>
                        )}
                      />
                    </div>
                  }
                  type="error"
                  showIcon
                  style={{ marginBottom: 24 }}
                />
              )}

              {/* 性能趋势图 */}
              <Row gutter={[16, 16]}>
                <Col span={12}>
                  <Card title="CPU & 内存趋势" size="small">
                    <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                      <div>
                        <LineChartOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                        <div>CPU & 内存使用率趋势图</div>
                        <div style={{ fontSize: 12 }}>需要集成图表库</div>
                      </div>
                    </div>
                  </Card>
                </Col>
                <Col span={12}>
                  <Card title="网络流量趋势" size="small">
                    <div style={{ height: 200, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                      <div>
                        <BarChartOutlined style={{ fontSize: 48, marginBottom: 16 }} />
                        <div>网络流量趋势图</div>
                        <div style={{ fontSize: 12 }}>需要集成图表库</div>
                      </div>
                    </div>
                  </Card>
                </Col>
              </Row>
            </div>
                )}
              </div>
            )
          },
          {
            key: 'services',
            label: <span><DesktopOutlined />服务监控</span>,
            children: (
              <Card>
                <Table
                  columns={serviceColumns}
                  dataSource={serviceStatuses}
                  rowKey="id"
                  size="small"
                  pagination={false}
                />
              </Card>
            )
          },
          {
            key: 'alerts',
            label: <span><BellOutlined />告警管理</span>,
            children: (
              <Row gutter={[16, 16]}>
                <Col span={24}>
                  <Card title="告警规则" size="small">
                    <Table
                      columns={ruleColumns}
                      dataSource={alertRules}
                      rowKey="id"
                      size="small"
                      pagination={{ pageSize: 10 }}
                    />
                  </Card>
                </Col>
                <Col span={24}>
                  <Card title="告警列表" size="small">
                    <Table
                      columns={alertColumns}
                      dataSource={alerts}
                      rowKey="id"
                      size="small"
                      pagination={{ pageSize: 10 }}
                    />
                  </Card>
                </Col>
              </Row>
            )
          },
          {
            key: 'performance',
            label: <span><ThunderboltOutlined />性能分析</span>,
            children: (
              <Row gutter={[16, 16]}>
                <Col span={24}>
                  <Card title="性能指标趋势" size="small">
                    <div style={{ height: 400, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>
                      <div>
                        <LineChartOutlined style={{ fontSize: 64, marginBottom: 16 }} />
                        <div style={{ fontSize: 18 }}>性能指标趋势图</div>
                        <div style={{ fontSize: 14 }}>包含响应时间、吞吐量、错误率等指标</div>
                        <div style={{ fontSize: 12 }}>需要集成图表库</div>
                      </div>
                    </div>
                  </Card>
                </Col>
              </Row>
            )
          }
        ]}
      />

      {/* 告警详情模态框 */}
      <Modal
        title="告警详情"
        open={alertModalVisible}
        onCancel={() => setAlertModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setAlertModalVisible(false)}>
            关闭
          </Button>,
          selectedAlert?.status === 'active' && (
            <Button 
              key="acknowledge" 
              onClick={() => {
                handleAcknowledgeAlert(selectedAlert.id);
                setAlertModalVisible(false);
              }}
            >
              确认告警
            </Button>
          ),
          selectedAlert?.status !== 'resolved' && (
            <Button 
              key="resolve" 
              type="primary"
              onClick={() => {
                if (selectedAlert) {
                  handleResolveAlert(selectedAlert.id);
                  setAlertModalVisible(false);
                }
              }}
            >
              解决告警
            </Button>
          )
        ].filter(Boolean)}
        width={600}
      >
        {selectedAlert && (
          <Descriptions column={1} bordered size="small">
            <Descriptions.Item label="规则名称">{selectedAlert.ruleName}</Descriptions.Item>
            <Descriptions.Item label="严重程度">
              <Tag color={getSeverityColor(selectedAlert.severity)}>
                {selectedAlert.severity === 'critical' ? '严重' : 
                 selectedAlert.severity === 'high' ? '高' : 
                 selectedAlert.severity === 'medium' ? '中' : '低'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="告警消息">{selectedAlert.message}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={getAlertStatusColor(selectedAlert.status)}>
                {selectedAlert.status === 'active' ? '活跃' : 
                 selectedAlert.status === 'acknowledged' ? '已确认' : '已解决'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="创建时间">{selectedAlert.createdAt}</Descriptions.Item>
            {selectedAlert.acknowledgedBy && (
              <Descriptions.Item label="确认人">{selectedAlert.acknowledgedBy}</Descriptions.Item>
            )}
            {selectedAlert.resolvedAt && (
              <Descriptions.Item label="解决时间">{selectedAlert.resolvedAt}</Descriptions.Item>
            )}
            <Descriptions.Item label="详细信息">
              <pre style={{ background: '#f5f5f5', padding: 8, borderRadius: 4, fontSize: 12 }}>
                {JSON.stringify(selectedAlert.details, null, 2)}
              </pre>
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default MonitoringCenter;